package pl.com.sthaether.mc.main.menu;

import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.util.converter.NumberStringConverter;
import pl.com.sthaether.mc.MCApplication;
import pl.com.sthaether.mc.config.MCCurrentState;
import pl.com.sthaether.mc.engine.data.MCColorRange;
import pl.com.sthaether.mc.engine.data.MCMapDataObject;
import pl.com.sthaether.mc.engine.data.MCSeriesColor;

import java.util.ArrayList;
import java.util.List;

public class MCMenu extends MenuBar {

    public MCMenu() {
        getMenus().addAll(initMenus());
        setUseSystemMenuBar(true);
    }

    private List<Menu> initMenus() {
        List<Menu> menus = new ArrayList<>();
        Menu file = new Menu("File");
        file.getItems().addAll(initFileMenu());
        menus.add(file);
        Menu map = new Menu("Map");
        map.getItems().addAll(initMapMenu());
        menus.add(map);
        Menu help = new Menu("Help");
        help.getItems().addAll(initHelpMenu());
        menus.add(help);
        return menus;
    }

    private List<MenuItem> initHelpMenu() {
        List<MenuItem> items = new ArrayList<>();

        MenuItem helpAbout = new MenuItem("About");
        helpAbout.setOnAction(event -> {


        });
        items.add(helpAbout);
        return items;
    }

    private List<MenuItem> initMapMenu() {
        List<MenuItem> items = new ArrayList<>();

        MenuItem editPreferences = new MenuItem("Preferences");
        editPreferences.setOnAction(event -> {
            final Stage dialog = new Stage();
            dialog.setTitle("Preferences");
            dialog.initModality(Modality.APPLICATION_MODAL);
            dialog.initOwner(MCApplication.getPrimaryStage());
            VBox dialogVbox = new VBox(20);
            TextField nameField = new TextField();
            nameField.textProperty().bindBidirectional(MCCurrentState.getInstance().getCurrentMap().getData().getMapName().textProperty());
            String oldName = nameField.getText();

            TextField cartogramField = new TextField();
            cartogramField.textProperty().bindBidirectional(MCCurrentState.getInstance().getCurrentMap().getData().getCartogramLegendText().textProperty());
            String oldCartogramName = cartogramField.getText();

            TextField cartodiagramField = new TextField();
            cartodiagramField.textProperty().bindBidirectional(MCCurrentState.getInstance().getCurrentMap().getData().getCartodiagramLegendText().textProperty());
            String oldCartodiagramName = cartodiagramField.getText();

            CheckBox showNames = new CheckBox("Show names");
            showNames.setSelected(MCCurrentState.getInstance().getCurrentMap().getData().getTextGroup().isVisible());

            CheckBox showLegend = new CheckBox("Show legend");
            showLegend.setSelected(MCCurrentState.getInstance().getCurrentMap().getData().getSeriesGroup().isVisible());

            HBox buttonsBox = new HBox();
            Button okButton = new Button("Confirm");
            okButton.setOnMouseClicked(e -> {
                MCCurrentState.getInstance().getCurrentMap().getData().getSeriesGroup().setVisible(showLegend.isSelected());
                MCCurrentState.getInstance().getCurrentMap().getData().getTextGroup().setVisible(showNames.isSelected());
                dialog.close();
            });
            Button cancelButton = new Button("Cancel");
            cancelButton.setOnMouseClicked(e -> {
                System.out.println("Canceled");
                nameField.setText(oldName);
                cartogramField.setText(oldCartogramName);
                cartodiagramField.setText(oldCartodiagramName);
                dialog.close();
            });
            buttonsBox.getChildren().addAll(okButton, cancelButton);

            dialogVbox.getChildren().addAll(new Label("Map tittle"), nameField, new Label("Cartogram legend"), cartogramField, new Label("Cartodiagram legend"), cartodiagramField, showNames, showLegend, buttonsBox);
            Scene dialogScene = new Scene(dialogVbox, 300, 350);
            dialog.setScene(dialogScene);
            dialog.show();
        });
        items.add(editPreferences);

        MenuItem cartogramPreferences = new MenuItem("Cartogram Pref");
        cartogramPreferences.setOnAction(event -> {
            final Stage dialog = new Stage();
            dialog.setTitle("Cartogram preferences");
            dialog.initModality(Modality.APPLICATION_MODAL);
            dialog.initOwner(MCApplication.getPrimaryStage());
            VBox dialogVbox = new VBox(20);
            TableView<MCColorRange> table = new TableView<>();
            table.setEditable(true);
            table.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
            table.getSelectionModel().setCellSelectionEnabled(true);
            TableColumn<MCColorRange, Number> fromColumn = new TableColumn<>("From");
            fromColumn.setPrefWidth(50);
            fromColumn.setCellValueFactory(cellData -> cellData.getValue().fromProperty());
            fromColumn.setCellFactory(TextFieldTableCell.<MCColorRange, Number>forTableColumn(new NumberStringConverter()));

            TableColumn<MCColorRange, Number> toColumn = new TableColumn<>("To");
            toColumn.setPrefWidth(50);
            toColumn.setCellValueFactory(cellData -> cellData.getValue().toProperty());
            toColumn.setCellFactory(TextFieldTableCell.<MCColorRange, Number>forTableColumn(new NumberStringConverter()));
            TableColumn<MCColorRange, Color> colorColumn = new TableColumn<>("Color");
            colorColumn.setCellValueFactory(new PropertyValueFactory<>("color"));
            colorColumn.setPrefWidth(140);
            colorColumn.setCellFactory(param -> {
                TableCell<MCColorRange, Color> cell =
                        new TableCell<MCColorRange, Color>() {
                            @Override
                            public void updateItem(Color c, boolean empty) {
                                if (c != null) {
                                    final ColorPicker cp = new ColorPicker();
                                    cp.setValue(c);
                                    setGraphic(cp);
                                    cp.setOnAction(t -> {
                                        getTableView().getItems().get(getTableRow().getIndex()).setColor(cp.getValue());
                                    });
                                }
                            }
                        };
                return cell;
            });
            table.getColumns().add(fromColumn);
            table.getColumns().add(toColumn);
            table.getColumns().add(colorColumn);

            table.getItems().addAll(MCCurrentState.getInstance().getCurrentMap().getData().getCartogramColorRange().getAll());

            HBox actionssBox = new HBox();
            Button addButton = new Button("Add");
            addButton.setOnMouseClicked(e -> table.getItems().add(new MCColorRange(0, 0, new Color(0, 0, 0, 1))));
            Button removeButton = new Button("Remove");
            removeButton.setOnMouseClicked(e -> table.getItems().remove(table.getSelectionModel().getSelectedItem()));
            HBox buttonsBox = new HBox();
            Button okButton = new Button("Confirm");
            okButton.setOnMouseClicked(e -> {
                MCCurrentState.getInstance().getCurrentMap().getData().getCartogramColorRange().setAll(table.getItems());
                MCCurrentState.getInstance().getCurrentMap().getData().updateLegend();
                MCCurrentState.getInstance().getCurrentMap().getData().autoColorByValues();
                dialog.close();
            });
            Button cancelButton = new Button("Cancel");
            cancelButton.setOnMouseClicked(e -> {

                dialog.close();
            });
            buttonsBox.getChildren().addAll(okButton, cancelButton);

            actionssBox.getChildren().addAll(addButton, removeButton);
            dialogVbox.getChildren().addAll(table, actionssBox, buttonsBox);
            Scene dialogScene = new Scene(dialogVbox, 300, 500);
            dialog.setScene(dialogScene);
            dialog.show();

        });
        items.add(cartogramPreferences);

        MenuItem cartodiagramPreferences = new MenuItem("Cartodiagram Pref");
        cartodiagramPreferences.setOnAction(event -> {
            final Stage dialog = new Stage();
            dialog.setTitle("Cartodiagram preferences");
            dialog.initModality(Modality.APPLICATION_MODAL);
            dialog.initOwner(MCApplication.getPrimaryStage());
            VBox dialogVbox = new VBox(20);
            TableView<MCSeriesColor> table = new TableView<>();
            table.setEditable(true);
            table.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
            table.getSelectionModel().setCellSelectionEnabled(true);
            TableColumn<MCSeriesColor, String> seriesColumn = new TableColumn<>("Series");
            seriesColumn.setPrefWidth(150);
            seriesColumn.setCellValueFactory(cellData -> cellData.getValue().nameProperty());
            seriesColumn.setCellFactory(TextFieldTableCell.forTableColumn());
            seriesColumn.setOnEditCommit(event1 -> {
                MCSeriesColor value = event1.getRowValue();
                String val = event1.getNewValue();
                if (val != null && !val.equals("")) {
                    if (!val.equals("Add") && event1.getOldValue().equals("Add")) {

                        table.getItems().add(new MCSeriesColor("Add", null));
                        value.setName(val);
                        value.setColor(new Color(0, 0, 0, 1));

                    } else {
                        value.setName(val);
                    }
                } else if (table.getItems().size() > 1 && !event1.getOldValue().equals("Add")) {
                    table.getItems().remove(table.getSelectionModel().getSelectedIndex());
                }
                table.layout();
            });


            TableColumn<MCSeriesColor, Color> colorColumn = new TableColumn<>("Color");
            colorColumn.setCellValueFactory(new PropertyValueFactory<>("Color"));
            colorColumn.setPrefWidth(140);
            colorColumn.setCellFactory(param -> {
                TableCell<MCSeriesColor, Color> cell =
                        new TableCell<MCSeriesColor, Color>() {
                            @Override
                            public void updateItem(Color c, boolean empty) {
                                if (c != null && !empty) {
                                    final ColorPicker cp = new ColorPicker();
                                    cp.setValue(c);
                                    setGraphic(cp);
                                    cp.setOnAction(t -> {
                                        getTableView().getItems().get(getTableRow().getIndex()).setColor(cp.getValue());
                                    });
                                }
                            }
                        };
                return cell;
            });
            table.getColumns().add(seriesColumn);
            table.getColumns().add(colorColumn);
            table.getItems().setAll(MCCurrentState.getInstance().getCurrentMap().getData().getCartodiagramSeries());

            if (table.getItems().size() < 1) {
                table.getItems().add(new MCSeriesColor("Add", null));
            }
            HBox buttonsBox = new HBox();
            Button okButton = new Button("Confirm");
            okButton.setOnMouseClicked(e -> {
                MCCurrentState.getInstance().getCurrentMap().getData().setCartodiagramSeries(table.getItems());
                MCCurrentState.getInstance().getCurrentMap().getData().updateLegend();
                MCCurrentState.getInstance().getCurrentMap().getData().updateMapObjectsSeries();
                for (MCMapDataObject o : MCCurrentState.getInstance().getCurrentMap().getData().getObjectsMap().values()) {
                    o.updateChart();
                }
                dialog.close();
            });
            Button cancelButton = new Button("Cancel");
            cancelButton.setOnMouseClicked(e -> {
                dialog.close();
            });
            buttonsBox.getChildren().addAll(okButton, cancelButton);

            dialogVbox.getChildren().addAll(table, buttonsBox);
            Scene dialogScene = new Scene(dialogVbox, 300, 450);
            dialog.setScene(dialogScene);
            dialog.show();

        });
        items.add(cartodiagramPreferences);
        return items;
    }


    private List<MenuItem> initFileMenu() {
        List<MenuItem> items = new ArrayList<>();
        MenuItem fileExport = new MenuItem("Export map");
        fileExport.setOnAction(event -> {
            MCCurrentState.getInstance().exportAction();
        });
        items.add(fileExport);
        MenuItem fileLoad = new MenuItem("Load map");
        fileLoad.setOnAction(event -> {
            MCCurrentState.getInstance().loadFileAction();
        });
        items.add(fileLoad);
        MenuItem fileExit = new MenuItem("Exit program");
        fileExit.setOnAction(event -> {
            MCApplication.showExitActionConfirm();
        });
        items.add(fileExit);

        return items;
    }

}
